﻿using Ross.OA.Dto;
using Ross.OA.EntityFramework.Model;
using Ross.OA.Repositories;
using Ross.OA.Services.Dto;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Ross.OA.Services
{
    public class CommDBService: RossOAppBase
    {
        public readonly IRepository<Employee, int> ReposityEmp;
        public readonly IRepository<Depart, int> ReposityDept;
        public readonly IRepository<POPlans, Guid> ReposityPOPlan;
        public readonly IRepository<POHeads, Guid> ReposityPOHead;
        public readonly IRepository<PODetails, Guid> ReposityPODetail;
        public readonly IRepository<POReciveDetail, Guid> ReposityPOReciveDetail;
        public readonly IRepository<Log_ApiLog, long> ApiLog;
        public Database database;
        public CommDBService()
        {
            ReposityEmp = new Repository<Employee, int>(dbContext);
            ReposityDept = new Repository<Depart, int>(dbContext);
            ReposityPOPlan = new Repository<POPlans, Guid>(dbContext);
            ReposityPOHead = new Repository<POHeads, Guid>(dbContext);
            ReposityPODetail = new Repository<PODetails, Guid>(dbContext);
            ReposityPOReciveDetail = new Repository<POReciveDetail, Guid>(dbContext);
            ApiLog = new Repository<Log_ApiLog, long>(dbContext);
            database = dbContext.Database;
        }

        public ResultDto<List<Employee>> GetEmployeeWithDept(int PageIndex, int PageSize, Expression<Func<Employee, bool>> predicate)
        {
            var result = ReposityEmp.GetPageList(PageIndex, PageSize, predicate);
            result.datas = result.datas.AsQueryable()
                .OrderByDescending(entity => entity.Id)
                .Include(entity => entity.DepartId)
                .ToList();
            return result;
        }
        /// <summary>
        /// 插入月度采购数据，排除重复值
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<List<POPlans>> InsertPOPlanDataAsync(List<POPlans> data)
        {
            List<POPlans> plans = new List<POPlans>();
            var month = data.FirstOrDefault().plan_month;
            var lists = ReposityPOPlan.GetAll().Where(x => x.plan_month == month);
            
            int n = 0;
            foreach (var item in data)
            {
                var obj = lists.FirstOrDefault(x=>x.supplier_code == item.supplier_code 
                && x.company_code == item.company_code
                && x.fits_code == item.fits_code 
                && x.plan_version == item.plan_version
                && x.factory_code == item.factory_code
                && x.batch_serial == item.batch_serial
                && x.purchase_gcode == item.purchase_gcode
                && x.Status == 0);
                if (obj == null)
                {
                    item.Id = Guid.NewGuid();
                    item.CreationTime = DateTime.Now;
                    await ReposityPOPlan.InsertAsync(item);
                    plans.Add(item);
                    n++;
                }
                else
                {
                    obj.plan_num = item.plan_num;
                    obj.diff_first_num = item.diff_first_num;
                    obj.diff_prev_num = item.diff_prev_num;
                    await ReposityPOPlan.UpdateAsync(obj);
                    plans.Add(item);
                    n++;
                }
            }
            return plans;
        }
        public async Task<List<PoData>> InsertPODataAsync(List<PoData> data)
        {
            List<PoData> plans = new List<PoData>();
            if (data!=null && data.Count > 0)
            {
                var month = data.FirstOrDefault().sap_create_date.Month;
                var lists = ReposityPOHead.GetAll().Where(x => x.sap_create_date.Month == month);

                int n = 0;
                foreach (var item in data)
                {
                    var obj = lists.FirstOrDefault(x => x.supplier_code == item.supplier_code 
                    && x.company_code == item.company_code
                    && x.order_code == item.order_code
                    && x.purchase_gcode == item.purchase_gcode
                    && x.Status == 0);
                    if (obj == null)
                    {
                        POHeads po = new POHeads();
                        po.Id = Guid.NewGuid();
                        po.CreationTime = DateTime.Now;
                        po.order_code = item.order_code;
                        po.company_code = item.company_code;
                        po.company_name = item.company_name;
                        po.supplier_code = item.supplier_code;
                        po.supplier_name = item.supplier_name;
                        po.supplier_contacts = item.supplier_contacts;
                        po.supplier_tele = item.supplier_tele;
                        po.sap_create_date = item.sap_create_date;
                        po.order_type = item.order_type;
                        po.order_type_name = item.order_type_name;
                        po.purchase_gcode = item.purchase_gcode;
                        po.purchase_gname = item.purchase_gname;
                        po.factory_code_list = item.factory_code_list;
                        var newObj = await ReposityPOHead.InsertAsync(po);
                        if (newObj != null)
                        {
                            foreach (var detail in item.data)
                            {
                                detail.Id = Guid.NewGuid();
                                await ReposityPODetail.InsertAsync(detail);
                            }

                        }
                        plans.Add(item);
                        n++;
                    }
                    else
                    {
                        obj.supplier_contacts = item.supplier_contacts;
                        obj.supplier_tele = item.supplier_tele;
                        obj.sap_create_date = item.sap_create_date;
                        obj.order_type = item.order_type;
                        obj.order_type_name = item.order_type_name;
                        obj.factory_code_list = item.factory_code_list;
                        await ReposityPOHead.UpdateAsync(obj);
                        var poditems = await ReposityPODetail.GetAllListAsync(x => x.order_code == obj.order_code);
                        foreach(var detail in poditems)
                        {
                            await ReposityPODetail.DeleteAsync(detail);
                        }
                        foreach (var detail in item.data)
                        {
                            detail.Id = Guid.NewGuid();
                            await ReposityPODetail.InsertAsync(detail);
                        }
                        plans.Add(item);
                        n++;
                    }
                }
            }
            return plans;
        }
        public DataTable GetPOPlanDatas()
        {
            DataTable dt = new DataTable();
            var lists = ReposityPOPlan.GetAll();
            return dt;
        }
        /// <summary>
        /// 设置采购订单接收详情
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public string SetPOReviceDetail(POReciveDetail dto)
        {
            try
            {
                var obj = ReposityPOReciveDetail
                    .GetAllList(x => x.order_code == dto.order_code && x.order_line == dto.order_line)
                    .FirstOrDefault();
                if (obj != null)
                {
                    dto.Id = obj.Id;
                    ReposityPOReciveDetail.Update(dto);
                }
                else
                {
                    dto.Id = Guid.NewGuid();
                    ReposityPOReciveDetail.Insert(dto);
                }
                return "ok";
            }
            catch(Exception ex)
            {
                return ex.Message;
            }
        }
        /// <summary>
        /// 数据库记录日志
        /// </summary>
        /// <param name="apiName"></param>
        /// <param name="askContent"></param>
        /// <param name="backTime"></param>
        /// <param name="backContent"></param>
        /// <returns></returns>
        public string WriteLog(string apiName,DateTime askTime, string askContent, DateTime backTime, string backContent)
        {
            try
            {
                var resp = ApiLog.Insert(new Log_ApiLog()
                {
                    ApiName = apiName,
                    AskContent = askContent,
                    AskTime = askTime,
                    BackContent = backContent,
                    BackTime = backTime,
                });
                return resp != null ? "ok" : "日志写入失败";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }
}
